#include "i2c.h"

void write_reg(__u8 chip_addr, __u8 add, __u8 val){
    char buf[2];
    buf[0] = add;
    buf[1] = val;
    if (ioctl(i2c_bus -> file, I2C_SLAVE, chip) < 0) {
        /* ERROR HANDLING; you can check errno to see what went wrong */
        exit(1);
    }
	  if (write(i2c_bus -> file, buf, 2) != 2) {
	    /* ERROR HANDLING: i2c transaction failed */
  	}
}

__u8 read_reg(__u8 chip_addr, __u8 add){
    char buf[1];
    buf[0] = add;
    if (ioctl(i2c_bus -> file, I2C_SLAVE, chip_addr) < 0) {
        /* ERROR HANDLING; you can check errno to see what went wrong */
        exit(1);
    }
    if (write(i2c_bus -> file, buf, 1) != 1){ // writing address
	    /* ERROR HANDLING: i2c transaction failed */
  	}
    if (read(i2c_bus -> file, buf, 1) != 1){ // reading one byte
	    /* ERROR HANDLING: i2c transaction failed */
  	}
    return buf[0];
}



void init_i2c(int nb){
  char filename[20];	  
  snprintf(filename, 19, "/dev/i2c-%d", nb);
  file = open(filename, O_RDWR);
  if (file < 0) {
  /* ERROR HANDLING; you can check errno to see what went wrong */
    exit(1);
  }
  i2c_bus = malloc(sizeof(i2c)); 
  i2c_bus -> nb = nb ;
  i2c_bus -> file = file ; 
}




